package com.lins.common.mp.service;

import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lins.common.common.enums.ExceptionCode;
import com.lins.common.common.enums.OperationType;
import com.lins.common.common.result.Head;
import com.lins.common.common.result.Result;
import com.lins.common.common.util.CheckUtils;
import com.lins.common.mp.dto.CommonBaseDto;
import com.lins.common.mp.exception.CRUDException;
import com.lins.common.mp.model.CommonBaseModel;
import com.lins.common.mp.result.ExRespResult;
import com.lins.common.mp.result.RespResult;
import org.springframework.stereotype.Service;

import java.sql.SQLException;


/**
 * @author linsir
 * @title: BaseServiceImpl
 * @projectName lins
 * @description: 基类, 所有的controller应继承该类
 * @date 2021/12/10 0:33
 */

@Service
public abstract class BaseServiceImpl<BM extends BaseMapper<M>, M extends CommonBaseModel, D extends CommonBaseDto> extends ServiceImpl<BM, M> implements IService<M> {


   protected abstract M toM(D d);
   protected abstract D toD(M m);

   public Result crud(D d)
   {
     // 检查参数是否为空，如果为空抛出异常
      CheckUtils.checkNotNull(d);
      Result result = new ExRespResult(ExceptionCode.BIZ_ERROR);

      M m = toM(d);

      if (d.getOperationType().equals(OperationType.ADD))
      {
         result = saveModel(m);
      }
      return  result;
   }

   /**
    * 通用添加
    *
    * */
   public Result saveModel(M m) {
      Result result = new  ExRespResult(ExceptionCode.BIZ_ERROR);
      try
      {
         if (save(m))
         {
            result = new RespResult<Boolean>(Boolean.TRUE);
         }
         else {
            throw new CRUDException(ExceptionCode.ADD_ERROR);
         }
      }
      catch (CRUDException e)
      {
         result = new ExRespResult(ExceptionCode.ADD_ERROR);
      }
      return result;
   }




}
